/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/17 18:39
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
(function (){
    "use strict";

    var api = {
        addKeywordUrl: '/system/search/add',
        getLists: '/system/search/getLists',
        editUrl: '/system/search/edit',
        removeUrl: '/system/search/removeItem'
    };

    sm.controller('admin-system-search-controller', ['$http', '$scope', 'Modal', function ($http, $scope, Modal){

        var bak = [];
        $scope.showNextPage = false;
        $scope.lists = [];
        $scope.page = {
            page: 1
        };
        $scope.add = {
            keyword: '',
            times:''
        };

        /**
         * 加载
         */
        function loadLists() {
            $http.get(api.getLists, {
                params: $scope.page
            }).success(function (res){
                if (res.state){
                    pushToLists(res.data.lists);
                    bak = angular.copy($scope.lists);
                    $scope.showNextPage = res.data.nextPage;
                }
            });
        }

        $scope.resetKeyword = function(index, id, keyword){
            if (!keyword) {
                return false;
            }

            if (keyword == bak[index]['keyword']){
                return false;
            }

            if (checkRepeat('keyword', index, keyword)){
                Modal.alert('关键词 "' + keyword + '" 已存在');
                return false;
            }

            $http.post(api.editUrl, {
                type: 'keyword',
                kId: id,
                keyword: keyword
            }).success(function(res) {
                if (res.state){
                    bak = angular.copy($scope.lists);
                } else {
                    var err = !res.error ? '修改失败' : res.error;
                    Modal.error(err);
                }
            });
        };

        $scope.loadMore = function () {
            $scope.page.page += 1;
            loadLists();
        };

        $scope.addKeyword = function () {

            if (!$scope.add.keyword){
                Modal.alert('关键字不能为空');
                return false;
            }

            if (!$scope.add.times) {
                $scope.add.times = 0;
            }

            $http.post(api.addKeywordUrl, $scope.add).success(function (res) {
                if (res.state) {
                    $scope.lists.unshift(res.data);
                    $scope.add.keyword = '';
                    $scope.add.times = '';
                } else {
                    var err = !res.error ? '关键词添加失败' : res.error;
                    Modal.error(err);
                }
            });


        };

        $scope.removeItem = function (index, id) {
            Modal.alert({
                'title': '您确定要删除此关键字吗?',
                'content': '关键词一旦删除将无法恢复,请谨慎操作.',
                'buttons': [{
                    name: '取消',
                    type: 'cancel'
                }, {
                    name: '确认删除',
                    event: function() {
                        doRemove(index, id);
                    }
                }]
            });
        };

        function doRemove(index, id) {
            $http.get(api.removeUrl, {
                params: {
                    'kId':id,
                    'action': 'removeItem'
                }
            }).success(function (res){
                if(res.state) {
                    $scope.lists.splice(index, 1);
                    bak = angular.copy($scope.lists)
                } else{
                    var err = res.error ? res.error : '删除失败';
                    Modal.error(err);
                }

            });
        }

        $scope.resetTimes = function(index, id, times){
            if (times == bak[index]['times']){
                return false;
            }

            $http.post(api.editUrl, {
                type: 'times',
                kId: id,
                times: times
            }).success(function(res) {
                if (res.state){
                    bak = angular.copy($scope.lists);
                } else {
                    var err = !res.error ? '修改失败' : res.error;
                    Modal.error(err);
                }
            });
        };

        /**
         * 检查重复
         * @param type
         * @param index
         * @param value
         * @returns {boolean}
         */
        function checkRepeat(type, index, value) {
            var repeat = false;
            angular.forEach(bak, function(val, key){
                if (type == 'times' && index == key){
                    if (val['times'] == value) {
                        repeat = true;
                    }
                }

                if (type == 'keyword' && val['keyword'] == value){
                    repeat = true;
                }
            });
            return repeat;
        }

        /**
         * 加入列表
         * @param lists
         * @returns {boolean}
         */
        function pushToLists(lists)
        {
            if (!lists || lists.length == 0){
                return false;
            }

            angular.forEach(lists, function(val){
                $scope.lists.push(val)
            });
        }

        loadLists();

    }]);

})();